package com.jimei.voucher.service.impl;

import com.google.code.kaptcha.Producer;
import com.jimei.voucher.exception.VoucherException;
import com.jimei.voucher.service.CaptchaService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.awt.image.BufferedImage;

/**
 * 图片验证码service实现类
 * author czj
 */
@Service("captchaService")
public class CaptchaServiceImpl  implements CaptchaService {

    @Autowired
    private Producer producer;

    @Override
    public BufferedImage getCaptcha(String uuid) {
        if(StringUtils.isBlank(uuid)){
            throw new VoucherException("uuid不能为空");
        }
        //生成文字验证码
        String code = producer.createText();

//        Captcha captchaEntity = new Captcha();
//        captchaEntity.setUuid(uuid);
//        captchaEntity.setCode(code);
//        //5分钟后过期
//        captchaEntity.setExpireTime(DateUtils.addDateMinutes(new Date(), 5));
//        this.insert(captchaEntity);

        return producer.createImage(code);
    }

    @Override
    public boolean validate(String uuid, String code) {
//        Captcha captchaEntity = this.selectOne(new EntityWrapper<Captcha>().eq("uuid", uuid));
//        if(captchaEntity == null){
//            return false;
//        }
//
//        //删除验证码
//        this.deleteById(uuid);
//
//        if(captchaEntity.getCode().equalsIgnoreCase(code) && captchaEntity.getExpireTime().getTime() >= System.currentTimeMillis()){
//            return true;
//        }

        return false;
    }
}
